package bm.com.project.server.common.controller;

import bm.com.framework.common.config.EnumRoute;
import bm.com.framework.common.resp.ResultVO;
import bm.com.framework.common.unit.FileUtils;
import jakarta.annotation.Resource;
import jakarta.servlet.ServletContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.util.HashMap;

@RestController
@RequestMapping(EnumRoute.CommonRoute.Base)
//@Api("公共文件上传模块")
@Slf4j
public class UploadsController {

    @Resource
    ServletContext servletContext;

    /**
     * 单个文件上传
     * @param file
     * @return
     */
    @PostMapping(EnumRoute.CommonRoute.upload.SINGLE_FILE)
    public ResultVO SingleFile(@RequestParam("file") MultipartFile file) {

        if (file.isEmpty()) {
            return ResultVO.error("文件不能为空");
        }

        try {

            HashMap<String, Object> obj = new HashMap<>();
            byte[] bytes = file.getBytes();
            String fileName = FileUtils.generateRandomFileName(file.getOriginalFilename());

            obj.put("size",bytes.length);
            obj.put("fileName",fileName);
            obj.put("fileType",file.getContentType());
            obj.put("filePath", FileUtils.getFilepath()+"/"+fileName);

            FileUtils.saveFile(file,FileUtils.getFilepath(),fileName);
            return ResultVO.success(obj);
        } catch (Exception e) {
            e.printStackTrace();
            ResultVO.error("上传失败");
        }

        return ResultVO.error("请上传正确格式的文件");
    }



}
